package com.ray.study.sample.test.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description
 *
 * @author r.shi 2020/03/30 13:46
 */
public class DomainHelper {

    public static final String REG_DOMAIN_FULL = "(?<=//)(.*?)((?=/)|(?=$))";

    public static String getFullDomain(String url) {
        return getDomain(url, REG_DOMAIN_FULL);
    }

    public static String getTopDomainWithOutPort(String url) {
        String topDomain = getTopDomain(url);
        if(topDomain.contains(":")){
            return topDomain.substring(0, topDomain.indexOf(":"));
        }
        return topDomain;
    }

    public static String getTopDomain(String url) {
        String fullDomain = getDomain(url, REG_DOMAIN_FULL);
        String[] split = fullDomain.split("\\.");
        String topDomain = null;
        if(split.length >= 2){
            topDomain = split[split.length-2] + "."+split[split.length-1];
        }else{
            topDomain = fullDomain;
        }
        return topDomain;
    }

    public static String getDomain(String url, String reg) {
        Pattern p = Pattern.compile(reg);
        Matcher m = p.matcher(url);
        String domain = null;
        while (m.find()) {
            domain = m.group();
        }
        return domain;
    }

}
